import os
import sys
import logging
from typing import Dict, Any
from fastmcp import FastMCP

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# 将当前目录添加到 Python 路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from service import DocFormatAgent

def create_sample_file(sample_path: str) -> None:
    """创建样本文档"""
    try:
        if not os.path.exists(sample_path):
            with open(sample_path, "wb") as f:
                f.write(b"\n")  # 写入一个空行
            logger.info(f"Created sample file at {sample_path}")
        else:
            logger.info(f"Sample file already exists at {sample_path}")
    except Exception as e:
        logger.error(f"Failed to create sample file: {str(e)}")
        raise

def create_directories() -> str:
    """创建必要的目录并返回样本文档路径"""
    try:
        # 创建必要的目录
        os.makedirs("sample_docs", exist_ok=True)
        os.makedirs("output_docs", exist_ok=True)
        logger.info("Created necessary directories")
        
        # 创建样本文档
        sample_path = os.path.join("sample_docs", "sample.docx")
        create_sample_file(sample_path)
        return sample_path
    except Exception as e:
        logger.error(f"Failed to create directories: {str(e)}")
        raise

# 创建 FastMCP 实例
mcp = FastMCP(
    "doc_format_agent",
    transport="streamable-http",
    host="0.0.0.0",
    port=8000,
    path="/mcp",
    log_level="INFO"
)

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

# 创建服务实例
sample_path = create_directories()
agent = DocFormatAgent(sample_path)

# 注册工具
register_tools(mcp, agent)

# 打印服务信息
logger.info("Service configuration completed")
logger.info(f"Available tools: {mcp.list_tools()}")

from service import DocFormatAgent

def register_tools(mcp: FastMCP, agent: DocFormatAgent) -> None:
    """注册工具"""
    try:
        @mcp.tool()
        def format_document(
            input_path: str,
            output_path: str,
            sample_path: str | None = None
        ) -> Dict[str, Any]:
            """Format a Word document

            Args:
                input_path (str): Path to input document
                output_path (str): Path to output document
                sample_path (str, optional): Path to sample document

            Returns:
                Dict[str, Any]: Format result
            """
            return agent.format_document(input_path, output_path, sample_path)
        logger.info("Registered format_document tool")
    except Exception as e:
        logger.error(f"Failed to register tools: {str(e)}")
        raise

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

# 将当前目录添加到 Python 路径
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
def format_document(
    input_path: str,
    output_path: str,
    sample_path: str | None = None
) -> Dict[str, Any]:
    """格式化文档"""
    try:
        # 创建服务实例
        agent = DocFormatAgent(sample_path)
        
        # 格式化文档
        result = agent.format_document(
            input_path=input_path,
            output_path=output_path,
            sample_path=sample_path
        )
        
        return {
            "status": "success",
            "message": "Document formatted successfully",
            "result": result
        }
    except Exception as e:
        return {
            "status": "error",
            "message": str(e)
        }
    finally:
        logger.info("Service configuration completed")

